﻿@using ActualLab.Fusion
@using ActualLab.Fusion.Blazor
@using ActualLab.Fusion.UI
@using CleanArchitecture.Blazor.Application.Common.Interfaces.Identity
@using CleanArchitecture.Blazor.Application.Features.Fusion


@inherits ComputedStateComponent<List<SessionInfo>>
@inject IOnlineUserTracker OnlineUserTracker
@inject IStringLocalizer<ActiveUserSession> L
@inject ICurrentUserAccessor SessionInfoAccessor
@if (State.HasValue && State.LastNonErrorValue.Any())
{
    <div class="d-flex flex-row gap-2 my-3 gap-2 my-3">
        @foreach (var user in State.LastNonErrorValue.OrderBy(u => u.UserId != currentUserId))
        {
            <MudBadge Color="Color.Success" Overlap="false" Dot="true" Bordered="true">
                @if (string.IsNullOrEmpty(user.ProfilePictureDataUrl))
                {
                    <MudAvatar title="@user.UserName">
                        @user.UserName.First()
                    </MudAvatar>
                }
                else
                {
                    <MudAvatar title="@user.UserName">
                        <MudImage Src="@user.ProfilePictureDataUrl"></MudImage>
                    </MudAvatar>
                }
            </MudBadge>
        }
    </div>
}
@if (State.Error is not null)
{
    <MudAlert Severity="Severity.Error">@State.Error.Message</MudAlert>
}


@code {

    private string sessionId = Guid.NewGuid().ToString();
    private string? currentUserId;
    [CascadingParameter] private Task<AuthenticationState> AuthState { get; set; } = default!;
    [Inject] private UIActionTracker UIActionTracker { get; init; } = null!;
    private TimeSpan UpdateDelay { get; set; } = TimeSpan.FromSeconds(5);
    protected override async Task OnInitializedAsync()
    {
        if (SessionInfoAccessor.SessionInfo!=null)
        {
            currentUserId = SessionInfoAccessor.SessionInfo?.UserId;
            await OnlineUserTracker.Initial(SessionInfoAccessor.SessionInfo);
        }
    }

    protected override ComputedState<List<SessionInfo>>.Options GetStateOptions()
     => new() { UpdateDelayer = new UpdateDelayer(UIActionTracker, UpdateDelay) };

    protected override Task<List<SessionInfo>> ComputeState(CancellationToken cancellationToken)
    {
        return OnlineUserTracker.GetOnlineUsers(cancellationToken);
    }

    public override async ValueTask DisposeAsync()
    {
        if (!string.IsNullOrEmpty(currentUserId)){
            await OnlineUserTracker.Clear(currentUserId);
        }
        GC.Collect();
    }
}
